package com.example.satu.quizcreator.quiz_creator;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.example.satu.quizcreator.quiz.Quiz;
import com.example.satu.quizcreator.R;
import com.example.satu.quizcreator.quiz_creator.interfaces.onBackPressedListener;
import com.example.satu.quizcreator.quiz_creator.interfaces.onFileLoad;
import com.example.satu.quizcreator.quiz_creator.interfaces.onFileRemoveClickListener;
import com.example.satu.quizcreator.quiz_creator.interfaces.onItemFocusChange;
import com.example.satu.quizcreator.quiz_creator.interfaces.onWarningThrow;
import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockFragmentActivity;

import java.util.ArrayList;
import java.util.List;

import roboguice.activity.event.OnCreateEvent;
import roboguice.event.Observes;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;

import static com.example.satu.quizcreator.quiz_creator.QuizCreatorActivity.FILE_TYPE.NON_FILE;

/**
 * Created by Satu on 2014-09-03.
 */
@ContentView(R.layout.quiz_creator_activity_layout)
public class QuizCreatorActivity extends RoboSherlockFragmentActivity
        implements ViewPager.OnPageChangeListener,
        ActionBar.TabListener, onItemFocusChange {

    public enum FILE_TYPE{
        IMAGE_TYPE,
        AUDIO_TYPE,
        VIDEO_TYPE,
        NON_FILE
    }

    public static final String EXTRA_QUIZ = "extra_quiz";
    public static final int RESULT_CODE_QUIZ_CREATED = 0;
    public static final int RESULT_CODE_CANCEL = 1;
    public static final int RESULT_LOAD_SOUND = 2;
    public static final int RESULT_LOAD_VIDEO = 3;
    public static final String DATA_TYPE = "data_type";
/*    public static final String VIDEO_TYPE = "video";
    public static final String AUDIO_TYPE = "audio";
    public static final String IMAGE_TYPE = "image";*/
    public static final String FILE_PATH = "file_path";
    private static int RESULT_LOAD_IMAGE = 1;
    @InjectView(R.id.viewpager)
    private ViewPager viewPager;

    private BaseFragmentPagerAdapter viewPagerAdapter;

    //private Answer_method_fragment answer_method_fragment;

    private com.example.satu.quizcreator.quiz_creator.quiz_details_fragment quiz_details_fragment;

    private QuestionCreatorFragment questionCreatorFragment;

    private Fragment focusFragment;

    private Menu actionMenu;

    private boolean fileActionsVisible = false;

    private onBackPressedListener onBackPressedListener;

    private int pageSelected = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


      //  listFragment = new QuestionListFragment();
      //  switchMainFragment(listFragment,R.id.fragment_container);

    }
    public void initializeViewPager(@Observes OnCreateEvent event){
        quiz_details_fragment = new com.example.satu.quizcreator.quiz_creator.quiz_details_fragment();
        questionCreatorFragment = new QuestionCreatorFragment();
        List<Fragment> fragments = new ArrayList<Fragment>();

        fragments.add(quiz_details_fragment);
        fragments.add(questionCreatorFragment);

        viewPagerAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setOnPageChangeListener(this);
    }
    public void initializeActionBar(@Observes OnCreateEvent event){
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        final ActionBar.Tab newsTab = actionBar.newTab().setText(getString(R.string.TEST_DETAILS));
        newsTab.setTabListener(this);

        actionBar.addTab(newsTab);

        final ActionBar.Tab agendaTab = actionBar.newTab().setText(getString(R.string.QUESTIONS_LIST));
        agendaTab.setTabListener(this);
        actionBar.addTab(agendaTab);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if(!(questionCreatorFragment instanceof onBackPressedListener))
            throw new RuntimeException("Twoj fragment nie implementuje onBackPressedListener");
        onBackPressedListener = questionCreatorFragment;

    }

    @Override
    public void onPageScrolled(int i, float v, int i2) {

    }

    @Override
    public void onPageSelected(int position) {
        getSupportActionBar().setSelectedNavigationItem(position);
        pageSelected = position;
        if(position == 0 && fileActionsVisible)
            setFilesMenuVisible(false,null);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        if(viewPager.getCurrentItem() != tab.getPosition())
            viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        actionMenu = menu;
        getSupportMenuInflater().inflate(R.menu.main_activity_actions,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_create_quiz :
                    createQuiz();
                    return true;
            case R.id.action_add_picture:
                    loadImage();
                    return true;
            case R.id.action_add_audio:
                loadSound();
                return true;
            case R.id.action_add_video:
                loadVideo();
                return true;
            case R.id.action_remove_file:
                removeFile();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private void createQuiz(){
        Quiz quiz = quiz_details_fragment.getQuiz();
        if (quiz != null) {
            quiz.setQuestions(questionCreatorFragment.getQuestions());
            if (quiz.getQuestionNumber() >= quiz.getQuestions().size() ) {
                if (quiz_details_fragment instanceof onWarningThrow)
                    quiz_details_fragment.warningThrow(getString(R.string.toMuchQuestionWarning));
                changePage(0);
                return;
            }
            Intent intent = new Intent();
            intent.putExtra(EXTRA_QUIZ, (android.os.Parcelable) quiz);
            setResult(RESULT_CODE_QUIZ_CREATED, intent);
            finish();
        }else {
            changePage(0);
        }
    }

    @Override
    public void onBackPressed() {
        boolean quit = false;
        if(pageSelected != 0)
            quit = onBackPressedListener.onBack();
        if(!quit || pageSelected == 0 )
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.dialog_ask_for_exit_title_pl))
                    .setMessage(getString(R.string.dialog_ask_exit_massage))
                    .setNegativeButton(android.R.string.no, null)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface arg0, int arg1) {
                            setResult(RESULT_CODE_CANCEL,null);
                            finish();
                        }
                    }).create().show();
    }

    @Override
    public void onItemFocus(boolean focus,Fragment fragment, FILE_TYPE file_type) {
          fileActionsVisible = focus;
          focusFragment = fragment;
          setFilesMenuVisible(focus,file_type);
    }
    private void setFilesMenuVisible(boolean visible,FILE_TYPE file_type){
        actionMenu.findItem(R.id.action_add_audio).setVisible(visible);
        actionMenu.findItem(R.id.action_add_picture).setVisible(visible);
        actionMenu.findItem(R.id.action_add_video).setVisible(visible);
        if(file_type != NON_FILE  )
            actionMenu.findItem(R.id.action_remove_file).setVisible(visible);
        if(file_type == NON_FILE && visible )
            actionMenu.findItem(R.id.action_remove_file).setVisible(false);
    }
    private void loadImage(){
        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }
    private void loadVideo(){
        Intent intent = new Intent(
                Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "Gallery"), RESULT_LOAD_VIDEO);
    }
    private void loadSound(){
        Intent i = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_SOUND);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // działania dla każdego wyboru pliku do wczytania
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

           // Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
            if(focusFragment != null)
                if(focusFragment instanceof onFileLoad){
                    Bundle bundle = new Bundle();
                    bundle.putInt(DATA_TYPE,FILE_TYPE.IMAGE_TYPE.ordinal());
                    bundle.putString(FILE_PATH,picturePath);
                   // bundle.putParcelable(IMAGE_TYPE,bitmap);
                    ((onFileLoad) focusFragment).onObjectLoad(bundle);
                }
            actionMenu.findItem(R.id.action_remove_file).setVisible(true);
        }
        if (requestCode == RESULT_LOAD_SOUND && resultCode == RESULT_OK && null != data) {
            Uri selectedSound = data.getData();
            String[] filePathColumn = { MediaStore.Audio.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedSound,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String soundPath = cursor.getString(columnIndex);
            cursor.close();
            /*File file = new File(soundPath);
            FileInputStream inputStream = null;
            byte[] buffer=null;
            try {
                inputStream = new FileInputStream(file);
                int size=0;
                    size = inputStream.available();
                    buffer = new byte[size];
                    inputStream.read(buffer);
                    inputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }*/
            if(focusFragment != null)
                if(focusFragment instanceof onFileLoad){
                    Bundle bundle = new Bundle();
                    bundle.putInt(DATA_TYPE,FILE_TYPE.AUDIO_TYPE.ordinal());
                    bundle.putString(FILE_PATH,soundPath);
                    //bundle.putByteArray(AUDIO_TYPE, buffer);
                    ((onFileLoad) focusFragment).onObjectLoad(bundle);
                }
            actionMenu.findItem(R.id.action_remove_file).setVisible(true);
        }
        if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK && null != data) {
            Uri selectedVideo = data.getData();
            String[] filePathColumn = { MediaStore.Video.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedVideo,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String videoPath = cursor.getString(columnIndex);
            cursor.close();
           /* File file = new File(videoPath);
            FileInputStream inputStream = null;
            byte[] buffer=null;
            try {
                inputStream = new FileInputStream(file);
                int size=0;
                size = inputStream.available();
                buffer = new byte[size];
                inputStream.read(buffer);
                inputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }*/
            if(focusFragment != null)
                if(focusFragment instanceof onFileLoad){
                    Bundle bundle = new Bundle();
                    bundle.putInt(DATA_TYPE,FILE_TYPE.VIDEO_TYPE.ordinal());
                    bundle.putString(FILE_PATH,videoPath);
                  //  bundle.putByteArray(VIDEO_TYPE,buffer);
                    ((onFileLoad) focusFragment).onObjectLoad(bundle);
                }
        }
        actionMenu.findItem(R.id.action_remove_file).setVisible(true);
    }
    private void removeFile(){
        if(focusFragment != null)
            if(focusFragment instanceof onFileRemoveClickListener){
                ((onFileRemoveClickListener) focusFragment).onFileRemoveClick();
                actionMenu.findItem(R.id.action_remove_file).setVisible(false);
            }
    }
    public void changePage(int toPage) {
        if(viewPager.getCurrentItem() != toPage)
            viewPager.setCurrentItem(toPage);
    }
}